export function numberToExcelColumn(num) {
  let result = "";
  while (num > 0) {
    num--; // 转换为 0-based，便于取模
    result = String.fromCharCode(65 + (num % 26)) + result;
    num = Math.floor(num / 26);
  }
  return result;
}
export function rowColToExcelAddress(row,col){
  return numberToExcelColumn(col+1)+''+(row+1);
}
export function excelAddressToRowCol(address) {
  // 去除空格并转为大写以增强鲁棒性
  address = address.trim().toUpperCase();

  // 使用正则分离字母部分（列）和数字部分（行）
  const match = address.match(/^([A-Z]+)(\d+)$/);
  if (!match) {
    throw new Error("Invalid Excel address format");
  }

  const colStr = match[1]; // 如 "A", "AB"
  const rowStr = match[2]; // 如 "1", "10"

  // 转换行：Excel 行号从 1 开始，我们转为从 0 开始
  const row = parseInt(rowStr, 10) - 1;

  // 转换列：A=0, B=1, ..., Z=25, AA=26, AB=27, ...
  let col = 0;
  for (let i = 0; i < colStr.length; i++) {
    col = col * 26 + (colStr.charCodeAt(i) - "A".charCodeAt(0));
  }

  return [row, col];
}
export function ptToPx(pt, dpi = 96) {
  if (typeof pt !== "number" || pt < 0) {
    throw new Error("输入必须是非负数字");
  }
  return (pt * dpi) / 72;
}
export function pxToPt(px, dpi = 96){
  if (typeof px !== "number") {
    throw new Error("输入必须是非负数字");
  }
  return (px * 72)/dpi
}
export function getRowHeight(height) {
  if(typeof height == 'number' && height >=0)
    return ptToPx(height)+'px';
  else
    return '30px';
}
export function getColumnWidth(colIndex, colsDefines) {
  const colDef = getColumnDefByIndex(colIndex,colsDefines);
  return getColumnWidthByDefine(colDef);
}
export function getColumnDefByIndex(colIndex,colsDefines){
  if (!colsDefines || colsDefines.length === 0) {
    return null
  }
  
  for (let colDef of colsDefines) {
    if (colDef.min <= colIndex + 1 && colIndex + 1 <= colDef.max) {
      return colDef;
    }
  }
  return null;
}
export function getRowDefByIndex(rowIndex,rowsDefines){
  if (!rowsDefines || rowsDefines.length === 0) {
    return null
  }
  
  for (let rowDef of rowsDefines) {
    if (rowDef.number == rowIndex + 1 ) {
      return rowDef;
    }
  }
  return null;
}
export function getColumnWidthByDefine(colDef){
  if(colDef && colDef.width!=null && colDef.width!=undefined)
    return colDef.width * 7.90 + "px";
  else{
    return 9 * 7.90 + "px";
  }
}
export function getMergeInside(rowIndex, colIndex, merges) {
  for (let merge of merges) {
    const [start, end]= merge.split(":");
    const [startRow, startCol] = excelAddressToRowCol(start);
    if (startRow <= rowIndex && startCol <= colIndex) {
      const [endRow, endCol] = excelAddressToRowCol(end);
      if (rowIndex <= endRow && colIndex <= endCol) {
        return { startRow, startCol, endRow, endCol };
      }
    }
  }
  return null;
}
export function xmlToObject(xmlString) {
  // 1. 解析 XML 字符串为 DOM 对象
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlString, "text/xml");

  // 2. 递归处理节点
  function parseNode(node) {
    // 处理文本节点
    if (node.nodeType === 3) {
      return node.textContent.trim() || null;
    }

    // 处理元素节点
    const result = {};
    const children = Array.from(node.childNodes).filter(
      (n) => n.nodeType === 1
    ); // 过滤元素节点

    // 处理属性
    if (node.attributes.length > 0) {
      result.$attributes = {};
      Array.from(node.attributes).forEach((attr) => {
        result.$attributes[attr.name] = attr.value;
      });
    }

    // 处理子节点
    if (children.length > 0) {
      children.forEach((child, index) => {
        const childData = parseNode(child);
        childData._index = index;
        // 处理重复节点（转为数组）
        const tagName =
          child.tagName.indexOf(":") >= 0
            ? child.tagName.split(":")[1]
            : child.tagName;
        if (result[child.tagName]) {
          if (!Array.isArray(result[child.tagName])) {
            result[tagName] = [result[child.tagName]];
          }
          result[tagName].push(childData);
        } else {
          result[tagName] = childData;
        }
      });
    } else {
      // 无子节点则取文本内容
      result.$value = node.textContent.trim() || null;
    }

    return result;
  }

  // 从根节点开始解析
  return parseNode(xmlDoc.documentElement);
}
export function getThemeColor(index, theme, tint = 0) {
  if (theme && theme.themeElements && theme.themeElements.clrScheme) {
    //从主题色中找到对应的颜色
    const clrScheme = theme.themeElements.clrScheme;
    const themeids = [
      "lt1",
      "dk1",
      "lt2",
      "dk2",
      "accent1",
      "accent2",
      "accent3",
      "accent4",
      "accent5",
      "accent6",
    ];
    const colorNode = clrScheme[themeids[index]];
    if (
      colorNode.srgbClr &&
      colorNode.srgbClr.$attributes &&
      colorNode.srgbClr.$attributes.val
    ) {
      return applyTint("#" + colorNode.srgbClr.$attributes.val, tint);
    } else if (
      colorNode.sysClr &&
      colorNode.sysClr.$attributes &&
      colorNode.sysClr.$attributes.lastClr != undefined
    ) {
      return applyTint("#" + colorNode.sysClr.$attributes.lastClr, tint);
    }
  } else {
    return null;
  }
}
function applyTint(color, tint) {
  // 1. 解析原始颜色为 RGB 数值
  let r, g, b;
  if (color.startsWith("#")) {
    // 处理 #RRGGBB 格式（如 #FF0000）
    const hex = color.slice(1);
    r = parseInt(hex.slice(0, 2), 16);
    g = parseInt(hex.slice(2, 4), 16);
    b = parseInt(hex.slice(4, 6), 16);
  } else if (color.startsWith("rgb")) {
    // 处理 rgb(r,g,b) 格式（如 rgb(255,0,0)）
    const rgbMatch = color.match(/\d+/g);
    r = parseInt(rgbMatch[0], 10);
    g = parseInt(rgbMatch[1], 10);
    b = parseInt(rgbMatch[2], 10);
  } else {
    throw new Error("不支持的颜色格式");
  }

  // 2. 统一 tint 为 0-1 的比例（处理 0-100000 格式）
  if (tint > 1) {
    tint = tint / 100000; // 例如 50000 → 0.5
  }
  // 限制 tint 在 (-1)~1 范围内
  tint = Math.max(-1, Math.min(1, tint));

  // 3. 按比例混合原始颜色和白色（255,255,255）
  // 公式：新颜色 = 原始颜色 * (1 - tint) + 白色 * tint
  let newR, newG, newB;
  if (tint > 0) {
    newR = Math.round(r * (1 - tint) + 255 * tint);
    newG = Math.round(g * (1 - tint) + 255 * tint);
    newB = Math.round(b * (1 - tint) + 255 * tint);
  }else{
    newR = Math.round(r * (1 + tint));
    newG = Math.round(g * (1 + tint));
    newB = Math.round(b * (1 + tint));
  }

  // 4. 转换为 #RRGGBB 格式
  const toHex = (num) => num.toString(16).padStart(2, "0").toUpperCase();
  return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`;
}
export function getColor(color, theme) {
  let resultColor = "";
  if (color && color.argb) {
    if (color.argb.length === 8) {
      resultColor = "#" + color.argb.slice(2);
    } else {
      resultColor = "#" + color.argb;
    }
  }
  if (color && color.theme >= 0) {
    resultColor = getThemeColor(color.theme, theme, color.tint || 0) || "none";
  }
  return resultColor;
}
import Enums from "./enums"
export function getCellTypeByValue(value){
  const v = value;
  if (v === null || v === undefined) {
    return Enums.ValueType.Null;
  }
  if (v instanceof String || typeof v === "string") {
    return Enums.ValueType.String;
  }
  if (typeof v === "number") {
    return Enums.ValueType.Number;
  }
  if (v instanceof Date) {
    return Enums.ValueType.Date;
  }
  if (v.text && v.hyperlink) {
    return Enums.ValueType.Hyperlink;
  }
  if (v.formula) {
    return Enums.ValueType.Formula;
  }
  return Enums.ValueType.Null;
}
export function isNumeric(str) {
  return /^-?\d*\.?\d+$/.test(str.trim());
}
